import Vue from "vue";
import Vuex from 'vuex';
import {getRequest} from "@/utils/api";
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
import {Notification} from 'element-ui'

Vue.use(Vuex)

const now = new Date();

const store = new Vuex.Store({
    state: {
        routes: [],
        sessions: {},
        users:[],
        currentAdmin: JSON.parse(window.sessionStorage.getItem('user')),
        currentSessionId: null,
        filterKey:'',
        stomp: null,
        idDot:{},
    },
    // 改变state中值时执行的方法
    // 同步执行
    mutations: {
        INIT_ADMIN(state,admin){
            this.state.currentAdmin = admin;
        },
        initRoutes(state, data) {
            state.routes = data;
        },
        changeCurrentSessionId(state, currentSessionId) {
            // console.log(currentSessionId);
            state.currentSessionId = currentSessionId;
            Vue.set(state.idDot, state.currentAdmin.username+'#'+state.currentSessionId.username, false);

        },
        addMessage(state, msg) {
            // console.log(msg);
            let mss = state.sessions[state.currentAdmin.username + '#'+msg.to];
            // console.log(mss);
            if(!mss){
                // state.sessions[state.currentAdmin.username + '#'+msg.to] = [];
                Vue.set(state.sessions,state.currentAdmin.username + '#'+msg.to,[]);
            }
            state.sessions[state.currentAdmin.username + '#'+msg.to].push({
                content: msg,
                date: new Date(),
                self: !msg.notSelf,
            })
        },
        INIT_DATA(state) {
            // 浏览器本地的历史聊天记录
            let data = localStorage.getItem('vue-chat-session');
            //console.log(data)
            if (data) {
                state.sessions = JSON.parse(data);
            }
        },
        INIT_ADMINS(state,data){
            // console.log(this);
            state.users = data;
            // this.state.users = data;
        },
    },
    // 异步执行
    actions: {
        connect(context){
            context.state.stomp = Stomp.over(new SockJS('/ws/ep'));
            let token = window.sessionStorage.getItem('tokenStr');
            context.state.stomp.connect({'Auth-Token':token},success=>{
                // 订阅消息  /user/queue/chat
                context.state.stomp.subscribe('/queue/chat',msg=>{
                    let receiveMsg = JSON.parse(msg.body);
                    if (!context.state.currentSessionId || receiveMsg.to !== context.state.currentSessionId.username){
                        // 提示消息
                        Notification.info({
                            title: `[${receiveMsg.from}]发来一条消息`,
                            message: receiveMsg.content.length > 10 ? receiveMsg.content.substr(0,10) : receiveMsg.content,
                            position: 'bottom-right'
                        });
                        Vue.set(context.state.idDot, context.state.currentAdmin.username+'#'+receiveMsg.from, true);
                    }
                    receiveMsg.to = receiveMsg.from;
                    receiveMsg.notSelf = true;
                    // console.log(receiveMsg);
                    // console.log(receiveMsg);
                    context.commit('addMessage', receiveMsg);
                })
            },error=>{

            })
        },
        initData (context) {
            getRequest('/chat/admin').then(resp=>{
                if (resp){
                    // console.log(resp)
                    context.commit('INIT_ADMINS', resp);
                }
            })
            context.commit('INIT_DATA')
        }
    }
})


store.watch(function (state) {
    return state.sessions
},function (val) {
    console.log('CHANGE: ', val);
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
},{
    deep:true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})


export default store;